package com.handinglian.ai.netty.client.handler;

import com.handinglian.ai.netty.client.GlobalConfig;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DecodeHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            String respStr = (String) msg;

            int packetLen = 0; // 当前读取包的长度
            int startPosition = 0; // 当前包开始位置
            int endPosition = 0; // 当前包结束位置
            try {
                GlobalConfig.AI_BUFFER.append(respStr + "\n");

                // 取得相应长度
                String regex = "<<<ip&port=(.*?),length=(.*?)>>>";
                Pattern pattern = Pattern.compile(regex);
                Matcher matcher = pattern.matcher(GlobalConfig.AI_BUFFER);
                if (matcher.find()) {
                    String group = matcher.group();
                    startPosition = matcher.end();// 得到结束的位置
                    // 得到数据长度
                    int endL = group.indexOf(">>>");
                    packetLen = Integer.parseInt(group.substring(group.indexOf("length=") + 7, endL));
                    endPosition = startPosition + packetLen;

                    if (GlobalConfig.AI_BUFFER.toString().getBytes("UTF-8").length >= endPosition) {
                        byte[] body = new byte[packetLen];
                        System.arraycopy(GlobalConfig.AI_BUFFER.toString().getBytes("UTF-8"), startPosition, body, 0,
                                packetLen);
                        System.out.println("receive="+new String(body, "UTF-8"));
                        endPosition = GlobalConfig.AI_BUFFER.indexOf(new String(body, "UTF-8"))
                                + (new String(body, "UTF-8")).length();
                        GlobalConfig.AI_BUFFER = new StringBuffer(
                                GlobalConfig.AI_BUFFER.toString().substring(endPosition));

                        super.channelRead(ctx, new String(body, "UTF-8"));
                    }
                }
            } catch (Exception er) {
                er.printStackTrace();
            }

        } finally {
            // 必须释放msg数据
            ReferenceCountUtil.release(msg);

        }

    }
}
